<!--慢sql分析-->
<template>
	<div class="app-container">
		<!--统计维度-->
		<el-form :model="queryParams" :inline="true" :label-width="100">
			<el-form-item label="执行时间" prop="systemId">
				<!--执行时间-->
				<el-date-picker
					v-model="queryParams.currentTime"
					:picker-options="oneDatePickerOptions"
					size="small"
					type="date"
					placeholder="选择日期"
					format="YYYY-MM-DD"
					value-format="YYYY-MM-DD"
					@change="getDate"
				></el-date-picker>
			</el-form-item>
			<el-row :gutter="10">
				<el-form-item label="时间段" prop="businessCodes">
					<!-- 统计维度-->
					<el-col v-for="(option, index) in options" :key="index" :span="0.5">
						<el-link
							:class="{ 'option-active': false ? option.isActive : currentIndex === index }"
							:underline="false"
							@click="handlerOptionClick(index, option.type)"
							>{{ option.label }}
						</el-link>
					</el-col>
				</el-form-item>
			</el-row>
		</el-form>

		<div class="div-content">
			<div style="padding: 20px">
				<el-row>
					<el-col :span="12">
						<svg-icon icon-class="cc-dot" style="color: #2beded; margin-right: 10px; font-size: 16px"></svg-icon>
						<span style="font-size: 16px; color: #ffffff">慢sql</span>
					</el-col>
					<el-col :span="12">
						<el-button type="primary" size="small" style="float: right; color: #1c2b5d" @click="getMore" v-if="mapData.length > 9"
							>查看更多
						</el-button>
					</el-col>
				</el-row>
			</div>
			<div class="div-content-data">
				<el-row>
					<el-col v-for="(data, index) in mapData" :key="index" :span="12">
						<div style="width: 95%; height: 80px; margin: 0 auto">
							<div class="progress">
								<div style="float: left">
									<el-button class="progress-title" size="small" type="text" @click="querySqlDetailHandler(data)">
										<span :style="{ color: typeIndexColor == data.index ? '#2beded' : '#fff' }">{{ data.bussType }}</span>
									</el-button>
								</div>
								<div style="float: right">
									<span class="progress-title-1">最大耗时：</span>
									<span class="progress-title-2">{{ toDecimalFormat(data.maxHandleTime) }}</span>
									<span class="progress-title-3"></span>
									<a>
										<i
											v-show="typeIndexColor == data.index"
											class="el-icon-caret-bottom"
											style="color: #2beded"
											@click="querySqlDetailHandler(data)"
										></i>
										<i v-show="typeIndexColor != data.index" class="el-icon-caret-left" @click="querySqlDetailHandler(data)"></i>
									</a>
								</div>
							</div>
							<div style="clear: both">
								<el-progress
									:percentage="getPercentage(data.avgHandleLength, data.maxHandleTime)"
									:stroke-width="10"
									:show-text="false"
								></el-progress>
							</div>
							<div class="progress-title-1">
								<span>平均耗时：</span>
								<span class="progress-title-2">{{ toDecimalFormat(data.avgHandleLength) }}</span>
								<span class="progress-title-3">(总数： {{ data.bussTypeCount }}次)</span>
							</div>
						</div>
					</el-col>
				</el-row>
			</div>
			<div v-if="mapData.length < 1" class="nodata-class">
				<svg-icon class-name="nodata" icon-class="nodata" style="width: 1.2rem"></svg-icon>
				<span style="padding-left: 5px">暂无数据~</span>
			</div>
		</div>
		<div class="div-content">
			<div style="padding: 20px">
				<el-row>
					<el-col :span="12">
						<svg-icon icon-class="cc-dot" style="color: #2beded; margin-right: 10px; font-size: 16px"></svg-icon>
						<span style="font-size: 16px; color: #ffffff">sql详情列表</span>
					</el-col>
				</el-row>
			</div>
			<YdTable
				:formData="queryParams"
				:tableConfig="tableConfig"
				:tableData="tableData"
				@sizeChangeHandler="querySqlDetail"
				@currentChangeHandler="querySqlDetail"
				@sortChangeHandler="querySqlDetail"
			>
			</YdTable>
			<!-- <el-table
				v-loading="loading"
				:data="tableData"
				border
				stripe
				:default-sort="{ prop: 'dealTime', order: 'descending' }"
				@sort-change="sortHandler"
			>
				<el-table-column type="index" label="序号" show-overflow-tooltip width="80" align="center">
					<template #default="scope">
						<span>{{ (queryParams.pageNum! - 1) * queryParams.pageSize! + scope.$index + 1 }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="bussType" label="资源编码" show-overflow-tooltip width="160"></el-table-column>
				<el-table-column prop="oriSql" label="原始sql" show-overflow-tooltip>
					<template #default="scope">
						<svg-icon class-name="copy2 copy-style" icon-class="copy2" @click="copyHandler(scope.row.oriSql)"></svg-icon>
						<span>{{ scope.row.oriSql }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="dealTime" label="耗时时长" show-overflow-tooltip width="120" :sortable="'custom'">
					<template #default="scope">
						<span>{{ toDecimalFormat(scope.row.dealTime / 1000) }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="startTvSec" label="执行时间" width="160">
					<template #default="scope">
						<span>{{ parseTime(scope.row.startTvSec) }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="requestIp" label="请求IP" show-overflow-tooltip width="160"></el-table-column>
				<el-table-column prop="responseIpStr" label="响应IP" show-overflow-tooltip width="160"></el-table-column>
				<template #empty>
					<div style="margin-top: 15%">
						<svg-icon class-name="nodata" icon-class="nodata" style="width: 1.2rem"></svg-icon>
						<span style="padding-left: 5px">暂无数据~</span>
					</div>
				</template>
			</el-table>
			<el-pagination
				v-model:current-page="queryParams.pageNum"
				v-model:page-size="queryParams.pageSize"
				style="height: 50px"
				class="yd-pagination"
				layout="total, sizes, prev, pager, next, jumper"
				:page-sizes="[10, 20, 30, 50, 100]"
				:total="total"
				@size-change="querySqlDetail"
				@current-change="querySqlDetail"
			/> -->
		</div>
	</div>
</template>
<script setup name="SqlAnalysis" lang="tsx">
import { getMap, getDetail } from '@/api/bpm/analysis/sql_analysis_api';
import { reactive, ref, computed, onMounted, getCurrentInstance, h } from 'vue';
import { parseTime, toDecimalFormate, copyMsg } from '@/utils/common';

const instance = getCurrentInstance();
const proxy = instance?.proxy;
const options = ref<any[]>([]);
const typeIndexColor = ref('');
const loading = ref(false);
const total = ref(0);
const size = ref(10);
// 结果集第一条数据的平均耗时
const firstAvgHandleLength = ref(0);
let queryParams = reactive<FormModelType>({
	currentTime: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
	timePiece: new Date().getHours(),
	pageNum: 1,
	pageSize: 10,
});
const mapData = ref<any[]>([]);
// options: initOption(),
const tableData = ref<any[]>([]);
//时间段
const currentIndex = ref<any>(new Date().getHours());
const oneDatePickerOptions = reactive<anyObj>({
	// 禁选日期
	disabledDate(time: Date) {
		return time.getTime() > Date.now();
	},
});

const tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '资源编码',
			prop: 'bussType',
		},
		{
			label: '原始sql',
			prop: 'oriSql',
			render(row: any, value: string) {
				let svgIocn = <svg-icon class-name="copy2 copy-style" icon-class="copy2" onClick="copyHandler(scope.row.oriSql)"></svg-icon>;
				// return (<svg-icon class-name="copy2 copy-style" icon-class="copy2" onClick="copyHandler(scope.row.oriSql)"></svg-icon><span> scope.row.oriSql </span>)
				let str = h(() => {
					return (
						<div>
							<svg-icon class-name="copy2 copy-style" icon-class="copy2" onClick={copyHandler.bind(this, row.oriSql)}></svg-icon>
							<span> {row.oriSql} </span>
						</div>
					);
				});
				{
					/* return (<svg-icon class-name="copy2 copy-style" icon-class="copy2" @click="copyHandler(scope.row.oriSql)"></svg-icon>
						<span> scope.row.oriSql </span>) */
				}
				return str;
			},
		},
		{
			label: '耗时时长',
			prop: 'dealTime',
			sortable: true,
			render(row: any, value: number) {
				return toDecimalFormat(value / 1000);
			},
		},
		{
			label: '执行时间',
			prop: 'startTvSec',
			render(row: any, value: number) {
				return parseTime(value);
			},
		},
		{
			label: '请求IP',
			prop: 'requestIp',
		},
		{
			label: '响应IP',
			prop: 'responseIpStr',
		},
	],
	pagination: {
		pageNum: 1,
	},
	loading: false,
});

onMounted(() => {
	initOption();
	proxy?.$nextTick(() => {
		initCharts();
	});
});

//初始化时间刻度
function initOption() {
	for (let i = 0; i < 24; i++) {
		options.value.push({
			type: i,
			label: i + '时',
		});
	}
	return options;
}

function initCharts() {
	initParams();
	queryMap();
}

/**
 * 数据查询
 */
function queryMap() {
	if (queryParams.currentTime === null) {
		return;
	}
	//   queryParams.timePiece = timeValue;
	queryParams.size = size.value;
	getMap(queryParams).then((res: ApiResponse) => {
		if (res.code === 0) {
			mapData.value = res.data;
			if (mapData.value.length > 0) {
				firstAvgHandleLength.value = mapData.value[0].avgHandleLength;
				queryParams.bussType = mapData.value[0].bussType;
				for (let i = 0; i < mapData.value.length; i++) {
					mapData.value[i].index = i;
				}
				typeIndexColor.value = mapData.value[0].index;
				querySqlDetail();
			}
		} else {
			mapData.value = [];
			proxy?.$message.warning(res.msg);
		}
	});
}

//查询
function querySqlDetailHandler(param: anyObj) {
	queryParams.bussType = param.bussType;
	typeIndexColor.value = param.index;
	querySqlDetail();
}

/**
 * 详情数据查询
 */
function querySqlDetail() {
	loading.value = true;
	console.log(queryParams.pageNum);
	getDetail(queryParams).then((res: ApiResponse) => {
		tableData.value = res.data.data;
		tableConfig.pagination!.total = res.data.total;
		loading.value = false;
	});
}

/**
 * 初始化参数
 */
function initParams() {
	queryParams.pageNum = 1;
	queryParams.pageSize = 10;
}

//查询
function searchHandler() {
	queryMap();
	tableData.value = [];
	tableConfig.pagination!.total = 0;
}

//时间选择
function getDate() {
	if (!queryParams.currentTime) {
		//所有清空
		currentIndex.value = undefined;
		mapData.value = [];
	} else {
		if (currentIndex.value === undefined) {
			currentIndex.value = new Date().getHours();
			queryParams.timePiece = currentIndex.value;
		}
	}
	tableData.value = [];
	total.value = 0;
	queryMap();
}

//查看更多
function getMore() {
	if (size.value > 10) {
		size.value = 10;
	} else {
		size.value = 20;
	}
	queryMap();
}

function copyHandler(sql: string) {
	if (copyMsg(sql)) {
		proxy?.$message.success('复制成功');
	}
}

// 点击选项
function handlerOptionClick(index: number, type: any, flag?: boolean) {
	queryParams.timePiece = type;
	// 单选模式
	if (currentIndex.value === index) {
		// 已经选中，不再触发搜索
		return;
	}
	// 选中样式
	currentIndex.value = index;
	if (!flag) {
		// 触发搜索事件
		searchHandler();
	}
}

/*时间格式转换*/
function toDecimalFormat(data: any) {
	return toDecimalFormate(data);
}

//获取比例(按照 结果集第一条数据的平均耗时 作为基准)
//测试说3.0逻辑错误，现改成平均耗时/最大耗时
function getPercentage(divisor: any, maxHandleTime: any) {
	return (divisor / maxHandleTime) * 100;
}

/**
 * 排序
 * @param column
 */
function sortHandler(column: any) {
	// tableSort(queryParams, column, querySqlDetail);
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.yd-search-form-item :deep(.el-input--mini .el-input__inner) {
	background-color: hsla(0, 0%, 100%, 0.1);
	border: 0;
	color: #fff;
}

.progress-title {
	font-size: 13px;
}

.progress-title-1 {
	color: #fff;
	padding-top: 5px;
}

.progress-title-2 {
	color: #ff9a0c;
}

.progress-title-3 {
	color: #00e5e5;
}

.pagination-class {
	text-align: center;
}

.bg-heatmap {
	background-color: #144c6e;
	border: unset;
	border-radius: 12px;
}

.map-title {
	width: 8%;
	height: 50px;
	margin-left: 10%;
	padding-top: 7px;
	text-align: center;
	background-color: rgb(28, 43, 93);
	border-radius: 0 0 12px 12px;
}

.copy-style {
	position: absolute;
	display: block;
	left: 98%;
	top: 15px;
}

.nodata-class {
	color: #76818f;
	font-size: 14px;
	position: absolute;
	left: 47%;
	top: 35%;
}

.div-content {
	margin-bottom: 20px;
	background-color: rgba(29, 39, 75, 0.31);
	border: unset;
	border-radius: 12px;
}

.div-content-data {
	height: 400px;
	overflow: auto;
}

.div-content-data::-webkit-scrollbar {
	width: 10px;
	height: 1px;
}

/* 滚动条 */
.div-content-data::-webkit-scrollbar-thumb {
	width: 10px;
	border-radius: 10px;
	background: #121c3d;
}

/* 轨道 */
.div-content-data::-webkit-scrollbar-track {
	border-radius: 10px;
	background: rgba(28, 43, 93, 0.5);
}

/* 分页 */
// .yd-pagination {
//   text-align: center;
//   // margin-top: 10px;

//   :deep(.el-pager) {
//     li {
//       color: #ffffff;
//       background-color: #ffffff00;

//       &:hover {
//         background-color: #84ffff;
//         color: #1c2b5d;
//         border-radius: 3px;
//       }

//       &.active {
//         background-color: #0097a7;
//         border-radius: 3px;
//         color: #ffffff;
//         cursor: default;
//       }
//     }
//   }
// }

:deep(.el-icon-caret-left) {
	color: #fff;
}
:deep(.el-link--default) {
	font-size: 14px;
	color: #fff;
	padding: 0 10px;
	background-color: hsla(0, 0%, 100%, 0.10196078431372549);
	border-radius: 8px;
	width: 100%;
}
.option-active {
	background-color: #1c2b5d !important;
}
</style>

<style></style>
